import StringTools;

class NumberUtils  {
	public static function formatFloat (i:Float) : String{
		var format:NumberFormat = NumberFormat.getInstance(null);
		return NumberUtils.format (i, 
			format.numDecimals, 
			format.isFixedNumDecimalsForced, 
			format.isDecimalSeparatorComma,
			format.isThousandSeparatorDisabled 
		);
	} 
	
	public static function formatFloatY2 (i:Float) : String{
		var format:NumberFormat = NumberFormat.getInstanceY2(null);
		return NumberUtils.format (i, 
			format.numDecimals, 
			format.isFixedNumDecimalsForced, 
			format.isDecimalSeparatorComma,
			format.isThousandSeparatorDisabled 
		);
	}	

	public static function format( 
		i:Float, 
		numDecimals:Float,
		isFixedNumDecimalsForced:Bool, 
		isDecimalSeparatorComma:Bool,
		isThousandSeparatorDisabled:Bool 
	) : String {
		if ( isNaN (numDecimals )) {
			numDecimals = 4;
		}
		
		// round the number down to the number of
		// decimals we want ( fixes the -1.11022302462516e-16 bug)
		i = Math.round(i*Math.pow(10,numDecimals))/Math.pow(10,numDecimals);
		
		var s:String = '';
		var num:Array<Dynamic>;
		if( i<0 )
			num = String(-i).split('.');
		else
			num = String(i).split('.');
		
		//trace ("a: " + num[0] + ":" + num[1]);
		var x:String = num[0];
		var pos:Int=0;
		var c:Int=0;
		c=x.length-1;
		while (c>-1)
		{
			if( pos%3==0 && s.length>0 )
			{
				s=','+s;
				pos=0;
			}
			pos++;
				
			s=x.substr(c,1)+s;
			c--;
		}
		if( num[1] != undefined ) {
			if (isFixedNumDecimalsForced){
				num[1] += "0000000000000000";
			}
			s += '.'+ num[1].substr(0,numDecimals);
		} else {
			if (isFixedNumDecimalsForced && numDecimals>0){
				num[1] = "0000000000000000";
				s += '.'+ num[1].substr(0,numDecimals);			
			}
			
		}
			
		if( i<0 )
			s = '-'+s;
		
		if (isThousandSeparatorDisabled){
			//s =  StringTools.replace(s,",","");
			s =  StringTools.replace(StringTools,s, ",", "");			
		}
		
		if (isDecimalSeparatorComma) {
			s = toDecimalSeperatorComma(s);
		}			
		return s;
	}
	
	public static function toDecimalSeperatorComma (value:String) : String
	{
		/*
		return value
			.replace(".","|")
			.replace(",",".")
			.replace("|",",")
		*/
		var str:String = value;
		str =  StringTools.replace(str, ".","|");
		str =  StringTools.replace(str, ",",".");
		return StringTools.replace(str, "|",",");		
	}

}
